﻿using System;
using System.Linq;
using System.Collections.Generic;
using Raven.Client;

namespace Actya.Core.Widgets
{
	public class WidgetService : IWidgetService
	{
		private readonly IDocumentSession _session;

		public WidgetService(IDocumentSession session)
		{
			_session = session;
		}

		public IWidget GetWidgetById(string id)
		{
			return _session.Load<dynamic>(id);
		}

		public IEnumerable<IWidget> GetWidgetsByIds(string[] widgetIds)
		{
			var widgets = _session.Load<dynamic>(widgetIds);
			return widgets.OfType<IWidget>();
		}

		public void Save<T>(T widget) where T : IWidget
		{
			_session.Store(widget);
			_session.SaveChanges();
		}

		public void Delete<T>(T widget) where T : IWidget
		{
			_session.Delete(widget);
			_session.SaveChanges();
		}

		public IWidget CreateWidget(WidgetType widgetType)
		{
			var widgetModelType = Type.GetType(widgetType.WidgetModelType, true);
			var widget = (IWidget)Activator.CreateInstance(widgetModelType);
			widget.WidgetTypeName = widgetType.Name;

			_session.Store(widget);
			_session.SaveChanges();

			return widget;
		}
	}
}